/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.camachosanchez.gui;

import com.camachosanchez.bean.Egresos;
import com.camachosanchez.bean.Pilotos;
import com.camachosanchez.bean.Vehiculos;
import com.camachosanchez.controler.jpa.EgresosJpaController;
import com.camachosanchez.controler.jpa.PilotosJpaController;
import com.camachosanchez.gui.textfield.MaxLengthTextDocument;
import com.camachosanchez.util.Constantes;
import com.camachosanchez.util.GUIUtil;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultComboBoxModel;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.WindowConstants;
import javax.swing.event.InternalFrameEvent;

/**
 *
 * @author ZULLY
 */
public class RegistroEgresos extends javax.swing.JInternalFrame {

    private Vehiculos unidad;

    /**
     * Creates new form RegistroEgresos
     */
    public RegistroEgresos() {
        initComponents();
        this.setSize(490, 360);
        GUIUtil.fondoBarraHerramientas(jToolBar1);
        this.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
        setFrameIcon(new ImageIcon(getClass().getResource("/com/camachosanchez/recursos/egreso.png")));
        this.addInternalFrameListener(new javax.swing.event.InternalFrameAdapter() {

            @Override
            public void internalFrameClosing(InternalFrameEvent e) {
                cerrar();
            }
        });
        llenarListasDesplegables();
        MaxLengthTextDocument doc = new MaxLengthTextDocument();
        doc.setMaxChars(10, Constantes.DECIMALES);
        txtMonto.setDocument(doc);
        txtMonto.setText("0.0");
        dateFecha.setDate(new Date());
    }

    private void cerrar() {
        GUIUtil.limpiarVentana(jPanel1.getComponents());
        GUIUtil.maximizarTodasLasVentanas(this);
    }

    public void llenarListasDesplegables() {
        PilotosJpaController dao_piloto = new PilotosJpaController(null);
        List<Pilotos> pilotos = dao_piloto.findPilotosEntities();
        comboPiloto.setModel(new DefaultComboBoxModel(pilotos.toArray()));
    }

    public void setUnidad(Vehiculos unidad) {
        this.unidad = unidad;
        this.txtVehiculo.setText(unidad.getPlaca());
        this.txtMonto.requestFocusInWindow();
        this.txtMonto.selectAll();
    }

    private boolean validar() {
        if (dateFecha.getDate() == null) {
            JOptionPane.showMessageDialog(this, "Ingrese una fecha válida.", "Datos incorrectos", JOptionPane.WARNING_MESSAGE);
            dateFecha.requestFocusInWindow();
            return false;
        }
        if (comboPiloto.getSelectedItem() == null) {
            JOptionPane.showMessageDialog(this, "Seleccione el piloto. Si no existe, regístrelo desde el menú Logística", "Datos incorrectos", JOptionPane.WARNING_MESSAGE);
            comboPiloto.requestFocusInWindow();
            return false;
        }
        if ((txtVehiculo.getText()).equals("") || this.unidad == null) {
            JOptionPane.showMessageDialog(this, "Especificar la unidad para la que se generó el egreso.", "Datos incorrectos", JOptionPane.WARNING_MESSAGE);
            btnBuscar.requestFocusInWindow();
            return false;
        }
        if ((txtMonto.getText()).equals("")) {
            JOptionPane.showMessageDialog(this, "Ingrese el monto del egreso.", "Datos incorrectos", JOptionPane.WARNING_MESSAGE);
            txtMonto.requestFocusInWindow();
            return false;
        }
        try {
            double monto = Double.parseDouble(txtMonto.getText());
        } catch (NumberFormatException e) {
            JOptionPane.showMessageDialog(this, "El monto ingresado no es correcto.", "Datos incorrectos", JOptionPane.WARNING_MESSAGE);
            txtMonto.requestFocusInWindow();
            return false;
        }
        if ((txtpConcepto.getText().trim()).equals("")) {
            JOptionPane.showMessageDialog(this, "Ingrese el concepto del egreso.", "Datos incorrectos", JOptionPane.WARNING_MESSAGE);
            txtpConcepto.requestFocusInWindow();
            return false;
        }
        return true;
    }

    private Egresos leerDatosEgreso() {

        Date fechaEgreso = dateFecha.getDate();
//        SimpleDateFormat sdt = new SimpleDateFormat("yyyyy-MM-dd");
//        String strFechaEgreso = sdt.format(fechaEgreso);
        Egresos egreso = new Egresos();
//        try {
        egreso.setFecha(fechaEgreso);
//        } catch (ParseException ex) {
//            JOptionPane.showMessageDialog(Principal.getInstance(), "La fecha ingresada no es correcta.", "Error", JOptionPane.ERROR_MESSAGE);
//        }
        egreso.setIdVehiculos(unidad);
        egreso.setIdPilotos((Pilotos) comboPiloto.getSelectedItem());
        egreso.setMonto(BigDecimal.valueOf(Double.parseDouble(txtMonto.getText())));
        egreso.setConcepto(txtpConcepto.getText());
        egreso.setTipo(Constantes.TIPO_VIGILANTE);
        egreso.setAnulado(false);
        egreso.setIdUsuarios(Constantes.currentUser);
        return egreso;
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        dateFecha = new com.toedter.calendar.JDateChooser();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jTabbedPane3 = new javax.swing.JTabbedPane();
        jScrollPane4 = new javax.swing.JScrollPane();
        txtpConcepto = new javax.swing.JTextPane();
        comboPiloto = new javax.swing.JComboBox();
        txtVehiculo = new javax.swing.JTextField();
        txtMonto = new javax.swing.JTextField();
        btnBuscar = new javax.swing.JButton();
        jLabel5 = new javax.swing.JLabel();
        jToolBar1 = new javax.swing.JToolBar();
        jPanel2 = new javax.swing.JPanel();
        btnGuardar = new javax.swing.JButton();

        setClosable(true);
        setIconifiable(true);
        setMaximizable(true);
        setResizable(true);
        setTitle(".:: Registro de egresos ::.");

        jPanel1.setBackground(new java.awt.Color(231, 239, 247));

        jLabel1.setText("Fecha:");

        dateFecha.setDateFormatString("dd/MM/yyyy");

        jLabel2.setText("Piloto:");

        jLabel3.setText("Unidad:");

        jLabel4.setText("Monto:");

        jTabbedPane3.setBackground(new java.awt.Color(188, 211, 226));
        jTabbedPane3.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N

        jScrollPane4.setBorder(null);

        txtpConcepto.setBorder(javax.swing.BorderFactory.createEmptyBorder(2, 2, 2, 2));
        txtpConcepto.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtpConceptoKeyTyped(evt);
            }
        });
        jScrollPane4.setViewportView(txtpConcepto);

        jTabbedPane3.addTab("Concepto", jScrollPane4);

        comboPiloto.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        txtVehiculo.setBackground(java.awt.SystemColor.inactiveCaptionBorder);
        txtVehiculo.setEditable(false);

        txtMonto.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
        txtMonto.setText("0.0");

        btnBuscar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/camachosanchez/recursos/buscar.png"))); // NOI18N
        btnBuscar.setToolTipText("Buscar");
        btnBuscar.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
        btnBuscar.setFocusable(false);
        btnBuscar.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        btnBuscar.setMaximumSize(new java.awt.Dimension(22, 22));
        btnBuscar.setMinimumSize(new java.awt.Dimension(22, 22));
        btnBuscar.setPreferredSize(new java.awt.Dimension(22, 22));
        btnBuscar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnBuscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnBuscarActionPerformed(evt);
            }
        });

        jLabel5.setFont(new java.awt.Font("Ebrima", 1, 12)); // NOI18N
        jLabel5.setText("REGISTRO DE EGRESOS");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jTabbedPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 468, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5, javax.swing.GroupLayout.DEFAULT_SIZE, 624, Short.MAX_VALUE)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(comboPiloto, javax.swing.GroupLayout.PREFERRED_SIZE, 326, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                        .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                            .addComponent(jLabel4)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(txtMonto))
                        .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                            .addComponent(jLabel3)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(txtVehiculo, javax.swing.GroupLayout.PREFERRED_SIZE, 126, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(btnBuscar, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(dateFecha, javax.swing.GroupLayout.PREFERRED_SIZE, 126, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );

        jPanel1Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jLabel1, jLabel2, jLabel3, jLabel4});

        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 13, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(dateFecha, javax.swing.GroupLayout.PREFERRED_SIZE, 19, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(5, 5, 5)
                        .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 9, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(comboPiloto, javax.swing.GroupLayout.PREFERRED_SIZE, 19, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel3)
                        .addComponent(txtVehiculo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(btnBuscar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtMonto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jTabbedPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 155, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(26, 26, 26))
        );

        getContentPane().add(jPanel1, java.awt.BorderLayout.CENTER);

        jToolBar1.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        jToolBar1.setFloatable(false);
        jToolBar1.setRollover(true);

        jPanel2.setBackground(new java.awt.Color(255, 255, 255));
        jPanel2.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 4, 4));

        btnGuardar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/camachosanchez/recursos/24_save.png"))); // NOI18N
        btnGuardar.setToolTipText("Nuevo");
        btnGuardar.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
        btnGuardar.setFocusable(false);
        btnGuardar.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        btnGuardar.setMaximumSize(new java.awt.Dimension(22, 22));
        btnGuardar.setMinimumSize(new java.awt.Dimension(22, 22));
        btnGuardar.setPreferredSize(new java.awt.Dimension(22, 22));
        btnGuardar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnGuardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGuardarActionPerformed(evt);
            }
        });
        jPanel2.add(btnGuardar);

        jToolBar1.add(jPanel2);

        getContentPane().add(jToolBar1, java.awt.BorderLayout.PAGE_START);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGuardarActionPerformed
        // TODO add your handling code here:
        if (validar()) {
            EgresosJpaController dao = new EgresosJpaController(null);
            dao.create(leerDatosEgreso());
            JOptionPane.showMessageDialog(this, "El registro de egresos ha finalizado correctamente.", "Operación finalizada", JOptionPane.INFORMATION_MESSAGE);
            cerrar();
            this.unidad = null;
        }
    }//GEN-LAST:event_btnGuardarActionPerformed

    private void txtpConceptoKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtpConceptoKeyTyped
        // TODO add your handling code here:
        String caracteres = this.txtpConcepto.getText();
        if (caracteres.length() >= 200) {
            evt.consume();
        }
    }//GEN-LAST:event_txtpConceptoKeyTyped

    private void btnBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnBuscarActionPerformed
        // TODO add your handling code here:
        DialogoBusquedaUnidad dlg = new DialogoBusquedaUnidad(this, Principal.getInstance(), true);
        dlg.setVisible(true);
    }//GEN-LAST:event_btnBuscarActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnBuscar;
    private javax.swing.JButton btnGuardar;
    private javax.swing.JComboBox comboPiloto;
    private com.toedter.calendar.JDateChooser dateFecha;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane4;
    private javax.swing.JTabbedPane jTabbedPane3;
    private javax.swing.JToolBar jToolBar1;
    private javax.swing.JTextField txtMonto;
    private javax.swing.JTextField txtVehiculo;
    private javax.swing.JTextPane txtpConcepto;
    // End of variables declaration//GEN-END:variables
}
